import { _decorator, Camera, Component, Node, Tween, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('CameraFollow')
export class CameraFollow extends Component {
    @property(Node)
    public target: Node = null; // 目标节点，即需要跟随的角色

    localPosition: Vec3;

    maxDistance: number = 50;
    private _flolow: boolean;

    start() {
        let tween = new Tween(this.node);
        this.schedule(() => {
            const targetPosition = this.target.position
            const localPosition = this.node.position
            
            let offset = new Vec3(0, 0, 0);
            if(Math.abs(targetPosition.x - localPosition.x) > this.maxDistance){
                offset.x = Math.sign(targetPosition.x - localPosition.x) * (Math.abs(targetPosition.x - localPosition.x) - 60);
            }else{
                offset.x = 0;
            }
            if(Math.abs(targetPosition.y - localPosition.y) > this.maxDistance){
                offset.y = Math.sign(targetPosition.y - localPosition.y) * (Math.abs(targetPosition.y - localPosition.y) - 60);
            }else{
                offset.y = 0;
            }
            console.log(offset);
            if(offset.x == 0 && offset.y == 0) return
            this._flolow = true;
            tween.to(0.3, {position: targetPosition}).start();
        }, 0.1);
    }

    update(deltaTime: number) {
        // this.node.lookAt(targetPosition);
    }
}
